import { i18n } from '@/common/utils';
import { BaseCommand, useCommandManager } from '@amcax/base';
import CaretRightOutlined from '@ant-design/icons/lib/icons/CaretRightOutlined';
import { Dropdown, MenuProps, Space } from 'antd';
import { Icon } from 'nextcae-base';
import { useState } from 'react';
import styles from './styles.module.scss';

type ExtendedMenuItem = MenuProps['items'][number] & {
  key: string;
  label: string;
  commands?: BaseCommand;
  children?: ExtendedMenuItem[];
};

type IProps = {
  items: ExtendedMenuItem[];
  showLabel?: boolean;
  icon?: string;
  disabled?: boolean;
  label?: string;
  noBg?: boolean;
};
export default function CmdDropDownMenu({
  items,
  label,
  icon,
  disabled,
  noBg = false,
}: IProps) {
  const [open, setOpen] = useState(false);
  const { invokeCmd } = useCommandManager();
  const processMenuItems = (items: ExtendedMenuItem[]): MenuProps['items'] => {
    return items.map((item) => {
      // 处理带子菜单的项
      if (item.children?.length) {
        return {
          key: item.key,
          title: i18n.t(item.label),
          children: processMenuItems(item.children),
          label: i18n.t(item.label), // 明确清空 label
          onClick: (info) => {
            info.domEvent.stopPropagation();
            setOpen(false);
            if (item.commands) invokeCmd(item.commands);
          },
        };
      }
      // 处理普通菜单项
      return {
        key: item.key,
        label: i18n.t(item.label), // ✅ 子项保持用 label
        onClick: (info) => {
          info.domEvent.stopPropagation();
          setOpen(false);
          if (item.commands) invokeCmd(item.commands);
        },
      };
    });
  };

  const menuItems = processMenuItems(items);
  return (
    <div className={styles['styled-split-button']}>
      <Space.Compact block>
        <Dropdown
          menu={{ items: menuItems }}
          trigger={['click']}
          open={open}
          onOpenChange={setOpen}>
          <div
            style={{ width: 'max-content', marginBottom: '5px' }}
            className={`${styles._self_drop_btn} ${open ? styles._self_drop_btn_active : ''} ${!noBg && styles._self_drop_btn_bg}`}>
            <Icon
              name={icon}
              style={{
                fontSize: '20px',
                opacity: disabled ? 0.3 : 1,
              }}
            />
            <div>{label && i18n.t(label)}</div>
            <CaretRightOutlined
              className={styles._self_drop_btn_icon}
              rotate={45}
            />
          </div>
        </Dropdown>
      </Space.Compact>
    </div>
  );
}
